import { GET } from '@/api'
import { middleware } from '@/utils/middleware'
import { clearToken } from '@/utils/token'
import { defineStore } from 'pinia'

/**
 * @description 储存用户信息，用于判断是否已经登录。
 */
export const userStore = defineStore('user', {
  persist: true,
  state: (): {
    userInfo: Record<string, string | number>
  } => ({
    userInfo: {
      name: '游客'
    }
  }),
  actions: {
    /**
     * @returns 返回用户信息
     */
    getUserInfo() {
      return this.userInfo
    },
    /**
     * @param 设置用户信息
     */
    setUserInfo(userInfo?: Record<string, string | number>) {
      if (!userInfo) {
        GET({ url: '/user/info' }).then((res) => {
          this.userInfo = res.data
        })
      }
      userInfo && (this.userInfo = userInfo)
    },
    /**
     * @description 清除用户信息
     */
    clearUserInfo() {
      this.userInfo = {
        name: '游客'
      }
    },
    /**
     * @description 退出登录
     */
    logout() {
      this.clearUserInfo()
      clearToken()
      middleware.emit('logout')
    }
  }
})
